package com.kabigon.pdf.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.extra.template.Template;
import cn.hutool.extra.template.TemplateConfig;
import cn.hutool.extra.template.TemplateEngine;
import cn.hutool.extra.template.TemplateUtil;
import cn.hutool.extra.template.engine.freemarker.FreemarkerEngine;
import com.aspose.words.Document;
import com.aspose.words.SaveFormat;
import com.documents4j.api.DocumentType;
import com.documents4j.api.IConverter;
import com.documents4j.job.LocalConverter;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
import com.kabigon.pdf.service.Word2PdfService;
import lombok.SneakyThrows;
import org.springframework.stereotype.Service;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;

@Service
public class Word2PdfServiceImpl implements Word2PdfService {

    @SneakyThrows
    @Override
    public void generatePdf() {
        //加载模板引擎
        TemplateConfig config = new TemplateConfig("templates");
        config.setCustomEngine(FreemarkerEngine.class);
        config.setResourceMode(TemplateConfig.ResourceMode.CLASSPATH);
        TemplateEngine templateEngine = TemplateUtil.createEngine(config);
        //加载ftl模板
        Template template = templateEngine.getTemplate("bzs.ftl");
        HashMap<String, Object> map = new HashMap<>();
        map.put("datetime", DateUtil.now());
        map.put("place", "北京市四合院小胡同");
        map.put("person", "我和小张");
        OutputStream outputStream = null;
        String dir = System.getProperty("system.dir");
        try {
            outputStream = FileUtil.getOutputStream("word2pdf/bzs.docx");
            //填充word模板
            template.render(map, outputStream);
            outputStream.flush();

        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            try {
                outputStream.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        //
        wordToPdfConvert();
        // 利用 jacob 转 pdf
        //convertWordToPdf("保证书.docx", "保证书.pdf");


    }


    @SneakyThrows
    public void wordHtml2ToPdfConvert() throws IOException {
        InputStream docxInputStream = FileUtil.getInputStream("word2pdf/保证书123.docx");

        //XHTMLOptions options = XHTMLOptions.create().indent(4);
        //OutputStream out = new FileOutputStream(new File("generated-doc.html"));
        //XHTMLConverter.getInstance().convert(document, out, options);
        FileOutputStream outputStream = new FileOutputStream("保证书.pdf");
        IConverter converter = LocalConverter.builder().build();
        converter.convert(docxInputStream).as(DocumentType.DOCX).to(outputStream).as(DocumentType.PDF).execute();
        outputStream.close();
        System.out.println("success");
        System.out.println("Word to PDF conversion completed.");

    }


    //todo ftl 转的暂不支持 word格式 保存为 PDF
    @SneakyThrows
    public void wordToPdfConvert1() throws IOException {
        InputStream docxInputStream = FileUtil.getInputStream("word2pdf/bzs.docx");
        //BufferedInputStream docxInputStream = FileUtil.getInputStream("D:\\projects\\kabigon-learning\\kabigon-tiny-pdf\\target\\test-classes\\word2pdf\\bzs.docx");
        FileOutputStream outputStream = new FileOutputStream("保证书.pdf");
        IConverter converter = LocalConverter.builder().build();
        converter.convert(docxInputStream).as(DocumentType.DOCX).to(outputStream).as(DocumentType.PDF).execute();
        outputStream.close();
        System.out.println("success");
        System.out.println("Word to PDF conversion completed.");

    }


    @SneakyThrows
    public void wordToPdfConvert() throws IOException {
        /*XWPFDocument doc = new XWPFDocument());// docx
        FileOutputStream outputStream = new FileOutputStream("保证书.pdf");
        Document pdfDocument = new Document();
        PdfWriter.getInstance(pdfDocument, outputStream);
        pdfDocument.open();
        for (XWPFParagraph paragraph : doc.getParagraphs()) {
            // 将 Word 段落内容添加到 PDF 中
            pdfDocument.add(new Paragraph(paragraph.getText()));
        }

        pdfDocument.close();
        System.out.println("Word to PDF conversion completed.");*/

        //加载 Word 文档
        Document doc = new Document(FileUtil.getInputStream("word2pdf/bzs.docx"));
        //将word 文档保存为pdf格式
        doc.save("output.pdf", SaveFormat.PDF);

    }

    // todo ftl 转的暂不支持 word格式 保存为 PDF
    public void convertWordToPdf(String inputPath, String outputPath) {
        ActiveXComponent app = new ActiveXComponent("Word.Application");
        try {
            app.setProperty("Visible", new Variant(false));
            Dispatch documents = app.getProperty("Documents").toDispatch();

            Dispatch document = Dispatch.invoke(documents, "Open", Dispatch.Method,
                    new Object[]{inputPath, false, true},
                    new int[1]).toDispatch();

            Dispatch.invoke(document, "SaveAs", Dispatch.Method,
                    new Object[]{outputPath, new Variant(17)},
                    new int[1]);

            Variant variant = new Variant(false);
            Dispatch.call(document, "Close", variant);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            app.invoke("Quit");
        }
    }
}









